import React, {Component} from "react";
import { Row, Col, Button, Input, Card, Pagination, message, Modal,Form, Upload, Image, Select } from 'antd'
import { ArrowLeftOutlined, SearchOutlined, PlusCircleOutlined, } from '@ant-design/icons'

import './index.less'
import { getAdmin, deleteAdmin, updateAdmin, addAdmin} from '../../api/admin'
import EditableTable from '../../components/tableItem/admin'
import rules from '../../utils/rules'

const { Option } = Select


class Admin extends Component {
  userRef = React.createRef();

  state = {
    admininfo: {
      hesdPortrait: '',
      srole: '管理员'
    },
    Issearch: false,
    searchList: [],
    keywords: '',
     params: {
      pageNum: 1,
      pageSize: 4,
      content: '',
     },
    total: 0,
    adminList: [],
    isModalVisible: false,
  }

  // 组件创建完成的生命周期
  componentDidMount() {
    this.getAdminList()
  }
  // 获取数据
  getAdminList = async () =>  {
   const res  = await getAdmin(this.state.params)
   const adminList = res.data.data
   adminList.map((item, value) => item.key = value)
   const total = res.data.total
   this.setState({adminList,total})
}

// 分页页面跳转
  paginationChange = (e) => {
     const params = {...this.state.params, pageNum: e }
     this.setState({params}, () => {
      this.getAdminList()
     })
}
// 监听enter点击事件
  onKeyup = (e) => {
    if(e.keyCode === 13) {
      this.getSearch()
  }
}
// 下拉选择
handleSelect = (value) => {
  const srole = value
  this.setState({admininfo: {...this.state.admininfo, srole}})
}

// 开始搜索
getSearch =  () => {
  this.setState({params: {...this.state.params, content:  this.state.keywords}}, async () => {
    const res  = await getAdmin(this.state.params)
    const searchList = res.data.data
    const total = res.data.total
    this.setState({searchList, Issearch: true, total})
  })
}

// 更新用户数据
updateList =  async (data) => {
  const res = await updateAdmin(data)
  if (res.code === 200) {
    message.success('更新数据成功')
  } else {
    message.error(res.msg)
  }
  this.getAdminList()
}
// 返回上一级
back = () => {
  const params = {...this.state.params, content: '', pageNum: 1 }
  this.setState({Issearch: false, params, keywords: ''}, () => {
    this.getAdminList()
  })
}

// 删除用户
deleteList = async (id) => {
  const res = await deleteAdmin(id)
  if (res.code === 200) {
    message.success('删除数据成功')
  } else {
    message.error('删除数据失败')
  }
  this.getAdminList()
}

// 气泡确认， 开始表单检验
handleOk =  () => {
  this.userRef.current.submit() 
}

// 表单验证失败
FormError = () => {
  message.error('表单数据有误')
 }

 // 图片上传
 handleChange = (info) => {
  if (info.file.status !== 'uploading') {
  }
  if (info.file.status === 'done') {
      const hesdPortrait = info.file.response.data.url
      this.setState({admininfo: {...this.state.admininfo,hesdPortrait}})
       message.success('图片上传成功');
  } else if (info.file.status === 'error') {
    message.error('图片上传失败');
  }
 }

 // 添加用户
adduser = async (values) => {
  const user = {...values,...this.state.admininfo}
  console.log(user)
  const res = await addAdmin(user)
  if (res.code === 200) {
    message.success('添加数据成功')
    this.setState({isModalVisible: false})
    this.getAdminList()
  } else {
    message.error(res.msg)
  }
}


  render() {
    const { adminList, total, params, isModalVisible, admininfo, Issearch, keywords, searchList } = this.state
    return (
        <div>
           <Row style={{ height: '46px', display: "flex", alignContent: "center"}}>
      <Col span={3}>{Issearch? <Button type="ghost" icon={<ArrowLeftOutlined />} onClick={() => this.back()} className="backBtn">返回</Button> : null }</Col>
      <Col span={6}><Input placeholder="搜索用户" prefix={<SearchOutlined />} value={keywords} onChange={(e) => {this.setState({keywords: e.target.value})}} onKeyUp={(e) => this.onKeyup(e)}></Input></Col>
      <Col span={2} offset={1}><Button type="primary" icon={<SearchOutlined />} onClick={() => this.getSearch()}>搜索</Button></Col>
      <Col span={2}><Button icon={<PlusCircleOutlined />} onClick={() => { this.setState({isModalVisible: true})}} className="successBtn">增加</Button></Col>
    </Row>
    <Card style={{marginTop: '30px'}}>
      {Issearch ?  <EditableTable data={searchList} updateList={(data) => {this.updateList(data)}} deleteList={(id) => {this.deleteList(id)}}></EditableTable> :  <EditableTable data={adminList} updateList={(data) => {this.updateList(data)}} deleteList={(id) => {this.deleteList(id)}}></EditableTable>}
    </Card>
    <div className="pagination">
   <Pagination showQuickJumper current={params.pageNum} total={total} onChange={this.paginationChange} pageSize={params.pageSize} />
    </div>
    {/* 添加框 */}
    <Modal title="添加用户" okText="确认" cancelText="取消" visible={isModalVisible} onOk={() => this.handleOk()} onCancel={() => {this.setState({isModalVisible: false})}}>
     <Form ref={this.userRef} onFinish={(values) => this.adduser(values)} onFinishFailed={this.FormError}>
         <Form.Item  label="用户名" name="username" rules={rules.userName}>
            <Input  />
            </Form.Item>
         <Form.Item  label="昵称" name="name" rules={rules.name}>
            <Input   />
            </Form.Item>
         <Form.Item  label="密码" name="password" rules={rules.password}>
            <Input />
            </Form.Item>
         <Form.Item  label="头像" name="purikura" rules={rules.purikura}>
         <Form.Item>
           <Upload  action="http://111.75.252.147:8888/app/scenic/picUpload" name="file" onChange={(info) => this.handleChange(info)}  >
           <Image  src={admininfo.hesdPortrait} fallback="" style={{width: '60px', height: '60px'}}></Image >
        </Upload>
           </Form.Item>
         </Form.Item>
         <Form.Item  label="角色" name="srole" >
           <Form.Item>
           <Select defaultValue={admininfo.srole} style={{ width: 120 }} onChange={(value) => this.handleSelect(value)}>
          <Option value="管理员">管理员</Option>
          <Option value="超级管理员">超级管理员</Option>
          </Select>
           </Form.Item>
          </Form.Item>
       </Form>
      </Modal>
        </div>
    );
  }
}

export default Admin;
